import VPlay 2.0
import QtQuick 2.0

import QtQuick.Controls 1.4
import QtWebSockets 1.0

import "../common"
import "../component"  as Component

SceneBase {
  id: gameScene
  // the filename of the current level gets stored here, it is used for loading the
  property string activeLevelFileName
  // the currently loaded level gets stored here
  property variant activeLevel
  // score
  property int score: 0
  // countdown shown at level start
  property int countdown: 0
  // flag indicating if game is running
  property bool gameRunning: countdown == 0

  property string ip
  property int port: 1234

  signal settingPressed

  // set the name of the current level, this will cause the Loader to load the corresponding level
  function setLevel(fileName) {
    activeLevelFileName = fileName
  }

  function setRobot(fileName, _ip) {
    activeLevelFileName = fileName
    ip = _ip
    socket.url = "ws://" + ip + ":" + port
  }

  function exit(disconnect_ip) {
    console.log("disconnect_ip = ", disconnect_ip)
    if (ip === disconnect_ip) {
      backButtonPressed()
      activeLevel = undefined
      activeLevelFileName = ""
      socket.active = false
    }
  }

  function sendPathCmd(cmd, number, dir) {
    var bytes = [0xAA, 0x78, 0x00, 0x00, 0xCC, 0x33, 0xC3, 0x3C]
    bytes[3] = dir
    console.log("bytes = ", bytes)
    socket.sendTextMessage(qsTr(bytes.toString()));
  }


  // background
  Rectangle {
    anchors.fill: parent.gameWindowAnchorItem
    color: "#47688e"
  }

  // back button to leave scene
  MenuButton {
    text: "返回"
    // anchor the button to the gameWindowAnchorItem to be on the edge of the screen on any device
    anchors.right: gameScene.gameWindowAnchorItem.right
    anchors.rightMargin: 10
    anchors.top: gameScene.gameWindowAnchorItem.top
    anchors.topMargin: 10
    onClicked: {
      backButtonPressed()
      activeLevel = undefined
      activeLevelFileName = ""
      socket.active = false
    }
  }

  // back button to leave scene
  MenuButton {
    text: "设置"
    // anchor the button to the gameWindowAnchorItem to be on the edge of the screen on any device
    anchors.right: gameScene.gameWindowAnchorItem.right
    anchors.rightMargin: 10
    anchors.bottom: gameScene.gameWindowAnchorItem.bottom
    anchors.bottomMargin: 20
    onClicked: {
      settingPressed()
    }
  }


  Component.Battery {
    id: battery
    anchors.left: gameScene.gameWindowAnchorItem.left
    anchors.leftMargin: 10
    anchors.top: gameScene.gameWindowAnchorItem.top
    anchors.topMargin: 10
  }


  // name of the current level
//  Text {
//    anchors.left: gameScene.gameWindowAnchorItem.left
//    anchors.leftMargin: 10
//    anchors.top: gameScene.gameWindowAnchorItem.top
//    anchors.topMargin: 10
//    color: "white"
//    font.pixelSize: 20
//    text: (activeLevel) ? activeLevel.levelName : ""
//  }


  // load levels at runtime
  Loader {
    id: loader
    source: activeLevelFileName != "" ? "../levels/" + activeLevelFileName : ""
    onLoaded: {
      // reset the score
      score = 0
      // since we did not define a width and height in the level item itself, we are doing it here
      item.width = gameScene.width
      item.height = gameScene.height
      // store the loaded level as activeLevel for easier access
      activeLevel = item
      // restarts the countdown
      countdown = 3

      socket.active = true
    }
  }
  // we connect the gameScene to the loaded level
  Connections {
    // only connect if a level is loaded, to prevent errors
    target: activeLevel !== undefined ? activeLevel : null
    // increase the score when the rectangle is clicked
    onRectanglePressed: {
      //console.log("onRectanglePressed code = ")
      // only increase score when game is running
      if(gameRunning) {
        score++
      }
    }
    onButtonPressed: {
      var bytes = [0xAA, 0x78, 0x00, 0x00, 0xCC, 0x33, 0xC3, 0x3C]
      bytes[3] = code

      socket.sendTextMessage(qsTr(bytes.toString()));
      //battery.setPower(code)
      //console.log("onButtonPressed code = ", code)
    }
  }

  // name of the current level
  Text {
    id: warning_text
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.top: gameScene.gameWindowAnchorItem.top
    anchors.topMargin: 10
    color: "red"
    font.pixelSize: 40
    text: ""
  }

//  // text displaying either the countdown or "tap!"
//  Text {
//    anchors.centerIn: parent
//    color: "white"
//    font.pixelSize: countdown > 0 ? 160 : 18
//    text: countdown > 0 ? countdown : "tap!"
//  }

  // if the countdown is greater than 0, this timer is triggered every second, decreasing the countdown (until it hits 0 again)
//  Timer {
//    repeat: true
//    running: countdown > 0
//    onTriggered: {
//      countdown--
//    }
//  }

  WebSocket {
    id: socket
    url: ""
    onTextMessageReceived: {
      var bytes = []
      for (var i = 0; i < message.length; i += 2) {
        bytes.push( parseInt(message.substr(i, 2), 16) )
      }
      var r_num = bytes[0]
      var r_type = bytes[1]
      var r_cmd = bytes[2]
      switch (r_type) {
      case 1:
        battery.setPower(r_cmd)
        break
      case 2:
        if (r_cmd === 1) {
          warning_text.text = "offline!!"
          warning_text.visible = true
        } else {
          warning_text.visible = false
        }
        break
      case 3:
        if (r_cmd === 1) {
          warning_text.text = "offline!!!"
          warning_text.visible = true
        } else {
          warning_text.visible = false
        }
        break
      case 4:
        if (r_cmd === 1) {
          warning_text.text = "offline!!!!"
          warning_text.visible = true
        } else {
          warning_text.visible = false
        }
        break
      default:
        break
      }

      //console.log(qsTr("Client received message: %1").arg(bytes))

      //console.log()
    }
    onStatusChanged: {
      console.log("onStatusChanged = ", socket.status)
      if (socket.status == WebSocket.Error) {
          console.log(qsTr("Client error: %1").arg(socket.errorString));
      } else if (socket.status == WebSocket.Closed) {
        backButtonPressed()
        console.log(qsTr("Client socket closed."));
      } else if (socket.status == WebSocket.Open) {

        //socket.sendTextMessage(qsTr("i am controller!!"));
      }
    }
  }
}
